package com.example.common.req;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "分页请求")
public class PageReq {

    @Schema(description = "页码")
    private int page;

    @Schema(description = "每页数量")
    private int size;

    @Schema(description = "排序")
    private List<Sort.Order> orders;

    public Pageable buildPageable() {
        if (0 == size) {
            size = 10;
        }
        if (CollectionUtils.isEmpty(orders)) {
            orders = new ArrayList<>();
            orders.add(new Sort.Order(Sort.Direction.DESC, "createTime"));
        }
        return PageRequest.of(page, size, Sort.by(orders));
    }
}
